package UDP_test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class ReciveMassage {
    public static void main(String[] args) throws IOException {
        //创建接收端的Socket对象 从指定端口接收
        DatagramSocket socket = new DatagramSocket(10086);
        //创建一个字节数组用于接收数据
        byte[] b=new byte[1024];
        //创建一个DatagramPacket对象 用于接收数据
        DatagramPacket packet = new DatagramPacket(b, b.length);
        //调用Socket对象的receive方法 接收数据
        while (true) {
            socket.receive(packet);

            byte[] data = packet.getData();
            int len = data.length;

            String str = new String(data, 0, len);
            String name = packet.getAddress().getHostName();
            String ip = packet.getAddress().getHostAddress();
            System.out.println("ip为" + ip + "，主机名为" + name + "发送了" + str);
        }
    }
}
